import pandas as pd
import numpy as np

import matplotlib

matplotlib.use('TkAgg')
import matplotlib.pyplot as plt


def read_data(file_path):
    data = pd.read_csv(file_path)
    return data.iloc[:, 1:]


def cost_function(x, y, theta):
    m = len(y)
    predictions = x.dot(theta)
    cost = (1 / (2 * m)) * np.sum(np.square(predictions - y))
    return cost


def gradient_descent(x, y, theta, alpha, iterations):
    m = len(y)
    cost_history = np.zeros(iterations)
    for i in range(iterations):
        for j in range(x.shape[1]):
            theta[j] -= (alpha / m) * np.sum((x.dot(theta) - y) * x[:, j])
        cost_history[i] = cost_function(x, y, theta)
        # print(cost_history[i])
    return theta, cost_history


data = (read_data('../data/world-happiness-report-2017.csv'))
y = np.array(data.iloc[:, 1])
x = np.array(data.iloc[:, 2:])
x_0 = np.ones((x.shape[0], 1))
x = np.concatenate((x_0, x), axis=1)
theta = np.zeros(x.shape[1])

a,b = gradient_descent(x, y, theta, 0.001, 100)

cost_x = np.linspace(1, 100, 100)
cost_y = b
plt.plot(cost_x, cost_y)
plt.show()

tem = [1,7.59444482058287,7.47955553799868,1.61646318435669,1.53352355957031,0.796666502952576,
       0.635422587394714,0.36201223731041,0.315963834524155,2.27702665328979]
tem2 = [1,3.73471479773521,3.47128505349159,0.368610262870789,0.640449821949005,0.277321130037308,0.0303698573261499,
        0.489203780889511,0.0998721495270729,1.69716763496399]
print(np.sum(theta.T.dot(np.array(tem))))
print(np.sum(theta.T.dot(np.array(tem2))))